package com.atlassian.jira.web.action.jimex;

import com.atlassian.jira.issue.MutableIssue;
import com.atlassian.jira.issue.fields.AffectedVersionsSystemField;
import com.atlassian.jira.issue.fields.ComponentsSystemField;
import com.atlassian.jira.issue.fields.FixVersionsSystemField;
import com.atlassian.jira.issue.fields.PrioritySystemField;
import com.atlassian.jira.web.action.issue.IssueCreationHelperBean;
import com.atlassian.jira.web.util.AttachmentException;
import com.atlassian.jira.web.util.WebAttachmentManager;
import com.atlassian.jira.config.SubTaskManager;
import com.atlassian.jira.config.ConstantsManager;
import net.sf.jimex.jira.JiraIssuesManager;
import net.sf.jimex.jira.JiraIssuesManagerImpl;
import net.sf.jimex.jira.JimexImportUtils;
import org.ofbiz.core.entity.GenericValue;
import webwork.action.ActionContext;
import webwork.multipart.MultiPartRequestWrapper;

import java.io.File;
import java.util.Collections;

/**
 * andrew 09.03.2006 23:30:58
 */
public class JimexImportProjectDetails extends JimexImportProject {
    protected MutableIssue issueObject;
    private IssueCreationHelperBean issueCreationHelperBean;
    private WebAttachmentManager attachmentManager;
    private static final String PROJECT_XML_FILE = "projectXmlFile";
    private JiraIssuesManagerImpl jiraIssuesManager;
    private static final String COMPONENTS = "components";
    private static final String VERSIONS = "versions";
    private static final String FIX_VERSIONS = "fixVersions";

    public JimexImportProjectDetails(IssueCreationHelperBean issueCreationHelperBean, JiraIssuesManager jiraIssuesManager, WebAttachmentManager attachmentManager, SubTaskManager subTaskManager, ConstantsManager constantsManager) {
        super(issueCreationHelperBean, subTaskManager, constantsManager);

        this.issueCreationHelperBean = issueCreationHelperBean;
        this.attachmentManager = attachmentManager;
        this.jiraIssuesManager = (JiraIssuesManagerImpl) jiraIssuesManager;
    }

    public String doDefault() throws Exception {
        getIssueObject().setProject(getSelectedProject());
        return super.doDefault();
    }

    protected void doValidation() {
        issueCreationHelperBean.validateLicense(this, this);
        super.doValidation();

        boolean isFileExists = true;
        MultiPartRequestWrapper multipart = getMultipart();
        try {
            isFileExists = attachmentManager.validateAttachmentIfExists(multipart, PROJECT_XML_FILE, false);
        } catch (AttachmentException e) {
            addError(PROJECT_XML_FILE, e.getMessage());
        }


        if (!invalidInput() && !isFileExists) {
            addErrorMessage(getText("attachfile.error.filerequired"));
            return;
        }

        String filesystemName = getSystemFileName();
        boolean isXmlFile = filesystemName.indexOf(".xml") > 0;

        if (!isXmlFile) {
            addErrorMessage("Wrong file format. Please, specify  XML Microsoft Project file ");
        }
    }

    private String getSystemFileName() {
        return getMultipart().getFilesystemName(PROJECT_XML_FILE);
    }

    protected String doExecute() throws Exception {
        ComponentsSystemField componentsSystemField = (ComponentsSystemField) getField(COMPONENTS);
        componentsSystemField.populateFromParams(getCustomFieldValuesHolder(), ActionContext.getParameters());
        AffectedVersionsSystemField affectedVersionsSystemField = (AffectedVersionsSystemField) getField(VERSIONS);
        affectedVersionsSystemField.populateFromParams(getCustomFieldValuesHolder(), ActionContext.getParameters());
        FixVersionsSystemField fixVersionsSystemField = (FixVersionsSystemField) getField(FIX_VERSIONS);
        fixVersionsSystemField.populateFromParams(getCustomFieldValuesHolder(), ActionContext.getParameters());
        PrioritySystemField prioritySystemField = (PrioritySystemField) getField("priority");
        prioritySystemField.populateFromParams(getCustomFieldValuesHolder(), ActionContext.getParameters());

        populateFieldHolderWithDefaults(getIssueObject(), Collections.EMPTY_LIST);

        File projectFile = getMultipart().getFile(PROJECT_XML_FILE);
        if (projectFile != null) {
            Long pid = getPid();
            jiraIssuesManager.init();
            jiraIssuesManager.setLinkType(getLinkType());
            jiraIssuesManager.setProjectId(pid);
            jiraIssuesManager.setComponents(componentsSystemField);
            jiraIssuesManager.setAffectedVersions(affectedVersionsSystemField);
            jiraIssuesManager.setFixVersions(fixVersionsSystemField);
            jiraIssuesManager.setPriority(prioritySystemField);
            jiraIssuesManager.setCustomFieldValuesHolder(getCustomFieldValuesHolder());
            jiraIssuesManager.setIssueType(getIssuetype());
            net.sf.jimex.ProjectManager projectManager = new net.sf.jimex.ProjectManager(jiraIssuesManager);
            projectManager.migrate(projectFile);
            GenericValue project = getIssueObject().getProject();
//            JimexImportUtils.saveImportedFile(project, projectFile, getSystemFileName());
            jiraIssuesManager.dispose();
            projectFile.delete();
        }

        return "success";
    }

    public GenericValue getIssue() {
        GenericValue issue = super.getIssue();
        if (issue == null) {
            throw new IllegalStateException("No issue has been created yet so it can not be retrieved");
        } else {
            return issue;
        }
    }
}
